<template style="overflow-y: scroll; overflow-x: hidden; height: 100%">
  <el-drawer
    :title="dialogStatus === 'create' ? '新建记录项' : '更新记录项'"
    size="61%"
    :visible.sync="visibility"
    custom-class="demo-drawer"
  >
    <div class="demo-drawer__content">
      <el-form
        ref="dataForm"
        :model="temp"
        :rules="rules"
        label-position="right"
        label-width="120px"
        style="width: 100%"
      >
        <el-form-item label="显示位置" prop="slot">
          <el-radio-group v-model="temp.slot">
            <el-radio :label="1">内容</el-radio>
            <el-radio :label="2">标题</el-radio>
            <el-radio :label="3">结尾</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="显示顺序" prop="sequence">
          <el-input v-model="temp.sequence" />
        </el-form-item>
        <el-form-item label="显示内容" prop="content">
          <div class="record-template-create-item-content">
            <el-row class="icon-button">
              <el-tooltip
                effect="dark"
                content="添加换行"
                placement="top-start"
              >
                <span
                  class="iconfont el-icon-allhuanhang"
                  @click="handleAddNewLine"
                />
              </el-tooltip>
              <el-tooltip
                effect="dark"
                content="添加选项"
                placement="top-start"
              >
                <span
                  class="iconfont el-icon-allxuanxiangka"
                  @click="handleOpenAddOption"
                />
              </el-tooltip>
              <el-tooltip
                effect="dark"
                content="添加填空"
                placement="top-start"
              >
                <span
                  class="iconfont el-icon-allhengxiangtiankong"
                  @click="handleOpenAddFill"
                />
              </el-tooltip>
              <el-tooltip
                effect="dark"
                content="添加表格"
                placement="top-start"
              >
                <span
                  class="iconfont el-icon-all24gl-table"
                  @click="handleOpenAddTable"
                />
              </el-tooltip>
              <el-tooltip
                effect="dark"
                content="添加图片"
                placement="top-start"
              >
                <span
                  class="iconfont el-icon-alltupian"
                  @click="handleOpenAddImage"
                />
              </el-tooltip>
              <el-tooltip
                effect="dark"
                content="添加视频"
                placement="top-start"
              >
                <span
                  class="iconfont el-icon-allshipin1"
                  @click="handleOpenAddVideo"
                />
              </el-tooltip>
            </el-row>
            <el-row style="margin-top: 6px">
              <div
                ref="htmlDiv"
                class="record-template record-template-create-item-preview"
              >
                &nbsp;
              </div>
            </el-row>
            <el-row style="margin-top: 6px">
              <el-input v-model="text" placeholder="请输入文本内容">
                <el-button
                  slot="append"
                  size="mini"
                  @click="
                    dialogType === 'create'
                      ? handleAddText()
                      : handleUpdateText()
                  "
                >
                  {{ tooltip }}
                </el-button>
              </el-input>
            </el-row>
          </div>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="temp.memo" />
        </el-form-item>
        <el-form-item>
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="handleCommit"> 确 定 </el-button>
        </el-form-item>
      </el-form>
      <AddOption
        :visible.sync="addOptionDialogVisible"
        :dialog-type="dialogType"
        :current-data="currentData"
        :dialog-title="dialogTitle"
        @add="handleAddOption"
        @update="handleUpdateOption"
      />
      <AddFill
        :visible.sync="addFillDialogVisible"
        :dialog-type="dialogType"
        :dialog-title="dialogTitle"
        :current-data="currentData"
        @add="handleAddFill"
        @update="handleUpdateFill"
      />
      <AddTable
        :visible.sync="addTableDialogVisible"
        :dialog-type="dialogType"
        :dialog-title="dialogTitle"
        :current-data="currentData"
        @add="handleAddTable"
      />
      <AddImage
        :visible.sync="addImageDialogVisible"
        :dialog-type="dialogType"
        :dialog-title="dialogTitle"
        :current-data="currentData"
        @add="handleAddImage"
      />
    </div>
    <div id="table" />
  </el-drawer>
</template>

<script>
import AddOption from './addOption.vue'
import AddFill from './addFill.vue'
import AddTable from './addTable.vue'
import AddImage from './addImage.vue'

import {
  saveRecordTemplateItem,
  updateRecordTemplateItem
} from '@/api/rs/recordTemplate'
import {
  PROTOCAL_SEGMENT_TEXT,
  toHtml,
  toTemplate,
  newLineToHtml,
  newLineToTemplate
} from '../scripts/text'
import { PROTOCAL_SEGMENT_OPTION } from '../scripts/option'
import { PROTOCAL_SEGMENT_FILL } from '../scripts/fill'
import { PROTOCAL_SEGMENT_TABLE } from '../scripts/table'
import { PROTOCAL_SEGMENT_IMAGE } from '../scripts/image'
// import TableRom from '@/views/manufacture/template/scripts/table-vue.vue'
// import Vue from 'vue/dist/vue.js'

export default {
  components: {
    AddOption,
    AddFill,
    AddTable,
    AddImage
    // TableRom
  },
  props: {
    visible: {
      required: true,
      type: Boolean
    },
    dialogStatus: {
      required: true,
      type: String
    },
    currentGroup: {
      type: Object,
      default: null
    },
    updateData: {
      type: Function,
      default: () => {}
    }
  },
  data() {
    return {
      loading: false,
      tableDataList: [],
      temp: {
        slot: 1,
        sequence: 1,
        content: ''
      },
      text: null,
      rules: {
        sequence: [
          { required: true, message: '显示顺序不可为空', trigger: 'blur' }
        ]
      },
      addOptionDialogVisible: false,
      addFillDialogVisible: false,
      addTableDialogVisible: false,
      addImageDialogVisible: false,
      editElementIdPrefix: 'XYE',
      lastEditElementId: null,
      dialogType: 'create',
      currentData: null,
      tooltip: '添加',
      dialogTitle: '新建'
    }
  },
  computed: {
    visibility: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  watch: {
    visible(value) {
      if (value) {
        this.reset()
      }
    },
    currentGroup(data) {
      console.log(data, 'w92929292929', this.dialogStatus)
      this.$nextTick(() => {
        if (this.dialogStatus === 'update') {
          this.temp = data
          data.template = data.content
          this.tableDataList.push(data)
          this.$refs['htmlDiv'].innerHTML = this.warpHtml(data)
        }
      })
    }
  },
  mounted() {
    window.openEdit = (id) => {
      this.openEdit(id)
    }
    window.handleRemove = (id) => {
      console.log(id)
      this.handleRemove(id)
    }
    window.handleOptionClick = (id) => {
      this.handleRemove(id)
    }
  },
  methods: {
    reset() {
      this.tableDataList = []
      this.temp = {
        slot: 1,
        sequence:
          this.currentGroup && this.currentGroup.itemList
            ? this.currentGroup.itemList.length + 1
            : 1,
        content: ''
      }
      this.text = null
      this.$nextTick(() => {
        this.$refs['htmlDiv'].innerHTML = '<i><内容预览></i>'
      })
    },
    handleEdit(row) {
      if (this.lastEditElementId) {
        document.getElementById(this.lastEditElementId).className = 'unselected'
      }
      document.getElementById(row.id).className = 'selected'
      this.lastEditElementId = row.id
      if (row.type === PROTOCAL_SEGMENT_TEXT) {
        this.text = '123'
      }
    },
    handleRemove(id) {
      const data = this.tableDataList || []
      data.forEach((e, index) => {
        if (e.id === id) {
          this.tableDataList.splice(index, 1)
          // row = e
        }
      })
      if (this.tableDataList.length === 0) {
        this.$refs['htmlDiv'].innerHTML = '<i><内容预览></i>'
      } else {
        this.$refs['htmlDiv'].innerHTML = ''
        this.tableDataList.forEach((e) => {
          this.$refs['htmlDiv'].innerHTML += this.warpHtml(e)
        })
      }
    },
    warpHtml(data) {
      const id = data.id
      const html = data.html
      return (
        '<span id="' +
        id +
        '"' +
        'class="P"' +
        'onClick ="openEdit(id' +
        ')"' +
        '>' +
        html +
        '</span>' +
        '<span id="' +
        id +
        '"' +
        'class="el-icon-circle-close" onClick="handleRemove(id)"></span>'
      )
    },
    handleAddText() {
      if (!this.text || this.text.trim().length === 0) {
        this.$message.warning('文本不能为空')
        return
      }
      if (this.tableDataList.length === 0) {
        this.$refs['htmlDiv'].innerHTML = ''
      }
      const params = {
        text: this.text
      }
      const data = {
        id: this.editElementIdPrefix + Math.random(),
        type: PROTOCAL_SEGMENT_TEXT,
        label: '文本',
        template: toTemplate(params),
        html: toHtml(params)
      }
      this.tableDataList.push(data)
      this.$refs['htmlDiv'].innerHTML += this.warpHtml(data)
      this.text = null
    },
    handleUpdateText() {
      const params = {
        text: this.text
      }
      const data = {
        id: this.currentData.id,
        type: PROTOCAL_SEGMENT_TEXT,
        label: '文本',
        template: toTemplate(params),
        html: toHtml(params)
      }
      this.newBuildHtml(this.currentData.id, data)
      this.tooltip = '添加'
      this.text = ''
      this.dialogType = 'create'
    },
    handleAddNewLine() {
      if (this.tableDataList.length === 0) {
        this.$refs['htmlDiv'].innerHTML = ''
      }
      const data = {
        id: this.editElementIdPrefix + Math.random(),
        type: PROTOCAL_SEGMENT_TEXT,
        label: '换行符',
        template: newLineToTemplate(),
        html: newLineToHtml()
      }
      this.tableDataList.push(data)
      this.$refs['htmlDiv'].innerHTML += this.warpHtml(data)
    },
    handleOpenAddOption() {
      this.dialogType = 'create'
      this.addOptionDialogVisible = true
    },
    handleAddOption(result) {
      if (this.tableDataList.length === 0) {
        this.$refs['htmlDiv'].innerHTML = ''
      }
      const data = {
        id: this.editElementIdPrefix + Math.random(),
        type: PROTOCAL_SEGMENT_OPTION,
        label: '选项',
        data: result.data,
        template: result.content,
        html: result.html
      }
      this.tableDataList.push(data)
      this.$refs['htmlDiv'].innerHTML += this.warpHtml(data)
    },
    handleUpdateOption(result) {
      const data = {
        id: result.id,
        type: PROTOCAL_SEGMENT_OPTION,
        label: '选项',
        data: result.data,
        template: result.content,
        html: result.html
      }
      this.newBuildHtml(result.id, data)
    },
    handleOpenAddFill() {
      this.addFillDialogVisible = true
    },
    handleAddFill(result) {
      if (this.tableDataList.length === 0) {
        this.$refs['htmlDiv'].innerHTML = ''
      }
      const data = {
        id: this.editElementIdPrefix + Math.random(),
        type: PROTOCAL_SEGMENT_FILL,
        label: '填空',
        template: result.content,
        html: result.html
      }
      this.tableDataList.push(data)
      this.$refs['htmlDiv'].innerHTML += this.warpHtml(data)
    },
    handleUpdateFill(result) {
      const data = {
        id: this.editElementIdPrefix + Math.random(),
        type: PROTOCAL_SEGMENT_FILL,
        label: '填空',
        template: result.content,
        html: result.html
      }
      this.newBuildHtml(result.id, data)
    },
    handleOpenAddTable() {
      this.addTableDialogVisible = true
    },
    handleAddTable(result) {
      console.log(result, 'iriririririri')
      if (this.tableDataList.length === 0) {
        this.$refs['htmlDiv'].innerHTML = ''
      }
      const data = {
        id: this.editElementIdPrefix + Math.random(),
        type: PROTOCAL_SEGMENT_TABLE,
        label: '表格',
        template: result.content,
        html: result.html
      }
      this.tableDataList.push(data)
      this.$refs['htmlDiv'].innerHTML += this.warpHtml(data)
    },
    handleOpenAddImage() {
      this.addImageDialogVisible = true
    },
    handleAddImage(result) {
      if (this.tableDataList.length === 0) {
        this.$refs['htmlDiv'].innerHTML = ''
      }
      const data = {
        id: this.editElementIdPrefix + Math.random(),
        type: PROTOCAL_SEGMENT_IMAGE,
        label: '图片',
        template: result.content,
        html: result.html
      }
      this.tableDataList.push(data)
      this.$refs['htmlDiv'].innerHTML += this.warpHtml(data)
    },
    handleOpenAddVideo() {
      //
    },
    handleAddVideo(result) {
      if (this.tableDataList.length === 0) {
        this.$refs['htmlDiv'].innerHTML = ''
      }
      const data = {
        label: '视频',
        template: result.content,
        html: result.html
      }
      this.tableDataList.push(data)
      this.$refs['htmlDiv'].innerHTML += data.html
    },
    handleClose(done) {
      // if (this.loading) {
      //   return
      // }
      if (this.tableDataList && this.tableDataList.length > 0) {
        this.$confirm('确定要提交表单吗？')
          .then((_) => {
            this.visibility = false
            done()
          })
          .catch((_) => {})
      } else {
        this.visibility = false
        done()
      }
    },
    handleCommit() {
      this.loading = true
      if (this.tableDataList.length === 0) {
        this.$message.warning('请输入内容')
        return
      }
      this.temp.recordTemplateId = this.currentGroup.recordTemplateId
      this.temp.recordTemplateGroupId = this.currentGroup.recordTemplateGroupId
      this.temp.content = ''
      this.tableDataList.forEach((e) => {
        this.temp.content += e.template
      })
      this.temp.segmentCount = this.tableDataList.length
      if (this.dialogStatus === 'update') {
        updateRecordTemplateItem(this.temp)
          .then((res) => {
            this.visibility = false
            this.$message.success('更新成功')
            this.$emit('update-data')
          })
          .finally(() => {
            this.loading = false
            //
          })
      } else {
        saveRecordTemplateItem(this.temp)
          .then((response) => {
            this.$message.success('新增成功')
            this.$emit('update-data')
            this.temp.sequence = this.temp.sequence + 1
            this.temp.content = ''
            this.tableDataList = []
            this.$refs['htmlDiv'].innerHTML = '<i><内容预览></i>'
          })
          .finally(() => {
            this.loading = false
          })
      }
    },
    openEdit(id) {
      const data = this.tableDataList || []
      data.forEach((e) => {
        if (e.id === id) {
          this.currentData = e
          this.dialogType = 'update'
          this.dialogTitle = '编辑'
          switch (e.type) {
            case '0':
              this.text = e.html
              this.tooltip = '提交修改'
              break
            case '1':
              this.addOptionDialogVisible = true
              break
            case '2':
              this.addFillDialogVisible = true
              break
            case '3':
              this.addTableDialogVisible = true
              break
            // case '4':
            //   this.addImageDialogVisible = true
            //   break
            // case '5':
            //   this.addOptionDialogVisible = true
            //   break
            default:
              break
          }
          // this.dataObj[Number(e.type)]
          // this.addOptionDialogVisible = true
        }
      })
    },
    /**
     * @description: 重新构建文本框HTML
     * @param {*} id 删除的dom
     * @param {*} data 新的dom
     * @return {*}
     */
    newBuildHtml(id, data) {
      this.tableDataList.forEach((e, index) => {
        if (e.id === id) {
          this.tableDataList.splice(index, 1, data)
        }
      })
      this.$refs['htmlDiv'].innerHTML = ''
      this.tableDataList.forEach((e) => {
        this.$refs['htmlDiv'].innerHTML += this.warpHtml(e)
      })
    }
  }
}
</script>

<style scoped lang='scss'>
.record-template-create-item-content {
  padding: 10px;
  border: solid 1px #dcdfe6;
  border-radius: 4px;
}
.record-template-create-item-preview {
  border: solid 1px #e4e7ed;
  border-radius: 5px;
  padding: 10px;
  min-height: 100px;

  .unselected {
    background-color: #ffffff;
    padding: 0px;
  }
  .selected {
    background-color: yellow;
    padding: 3px;
  }
  .P {
    height: 20px;
    margin-right: 20px;
  }
  .icon-button {
    background-color: #f06;
    border: 0px solid #000 !important;
  }
}
</style>>
